import { useEffect, useState, useCallback } from "react";
import i18n from "i18n-js";
import Taro, { getSystemInfoSync, useRouter } from "@tarojs/taro";
import PageContainer from "@/components/PageContainer";
import { DynamicColors, GStyleSheet } from "@/utils/DarkMode";
import { View } from "@tarojs/components";
import { GButton } from "@/components/GButton";
import DashedTitle from '@/components/DashedTitle';
import IconInput from "@/components/IconInput";
import Toast from "@/utils/Toast";
import wifiSelIcon from "../assets/wifi_icon_2.4g.png";
import passwordIcon from "../assets/icon_password.png";
import bluetoothIcon from "../assets/wifi_icon_bluetooth.png";
import locationIcon from "../assets/wifi_icon_position.png";
import wifiIcon from "../assets/WiFiIcon.png";
import TipItem from "./components/TipItem";
import configWifiModel from "../models/configWifi";


const dstyles = GStyleSheet.create({
  page: {
    backgroundColor: DynamicColors.normalBackgroundColor,
  },
  container: {
    width: "100%",
    height: "100%",
    padding: "32rpx",
    boxSizing: "border-box",
    borderTop: "1rpx solid rgba(0,0,0,0.1)",
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between'
  },
  desc: {
    width: "100%",
    padding: "40rpx 80rpx",
    boxSizing: "border-box",
    backgroundColor: "#fafafa",
  },
});

function getSystemVersion(system) {
  // 格式如：iOS 14.4.1，返回 144.1，可以直接用小数大小判断版本，不用担心三个.情况
  const arr = system.split(" ");
  if (arr && arr.length > 1) {
    const versionString = arr[1];
    const versionArr = versionString.split(".");
    if (versionArr && versionArr.length > 0) {
      let ver = versionArr[0] * 10;
      if (versionArr.length > 1) {
        ver += versionArr[1] * 1;
        if (versionArr.length > 2) {
          ver += versionArr[2] * 0.1;
        }
      }
      return ver;
    }
    return null;
  }
  return null;
}

const tips = [
  { icon: wifiSelIcon, text: '24G_TIP' },
  { icon: bluetoothIcon, text: 'NEED_OPEN_BLUETOOTH' },
];
const locationToConnectDeviceTip = 'NEED_LOCATION_TO_CONNECT';
const locationToGetWifiTip = 'NEED_LOCATION_TO_WIFI';

const SelectWifiPage = () => {
  const styles = dstyles.useDynamicStyle();
  const { params: { isAddWifi } } = useRouter<{ isAddWifi: string }>()
  const addWifi = isAddWifi === '1';
  const [locationTip, setLocationTip] = useState<{
    icon: string;
    text: string;
  }>();
  const [isUserInput, setUseInput] = useState(false);
  const [ssid, setSsid] = useState(configWifiModel.wifiName);
  const [password, setPassword] = useState(configWifiModel.password);

  useEffect(() => {
    const systemInfo = getSystemInfoSync();
    if (systemInfo.platform === "ios") {
      // setLocationTip({ icon: locationIcon, text: locationToGetWifiTip });
    } else if (systemInfo.platform === "android") {
      const systemVersion = getSystemVersion(systemInfo.system);
      if (systemVersion) {
        if (systemVersion < 80.0) {
          // 8.0以下，不需要定位权限，也不需要系统开启位置信息就能使用蓝牙搜索到设备，以及获取wifi名称
        } else if (systemVersion <= 81.0) {
          // 8.0以上 8.1.0以下，需要定位权限，需要系统开启位置信息才能获取wifi名称
          setLocationTip({ icon: locationIcon, text: locationToGetWifiTip });
        } else {
          // 8.1.0 以上 需要定位权限，蓝牙才能搜索到设备
          setLocationTip({
            icon: locationIcon,
            text: locationToConnectDeviceTip,
          });
        }
      }
    }
  }, []);

  useEffect(() => {
    setLocationTip({
      icon: locationIcon,
      text: locationToConnectDeviceTip,
    });
  }, [])

  const updateWifiToModel = useCallback((wifiName: string) => {
    const noSame = ssid !== wifiName;
    setSsid(wifiName);
    configWifiModel.getWifiInfoINLocalByWifiName(wifiName).then((res) => {
      if (res && res.wifiName) {
        const { password: pw, isManualInput } = res;
        setPassword(pw || '');
        setUseInput(isManualInput);
      } else {
        if (noSame) {
          setPassword('');
          setUseInput(false);
        }
      }
    });
  }, [ssid]);

  const getSSID = useCallback(() => {
    console.log('getSSID');
    if (!isUserInput) {
      Taro.getConnectedWifi({
        success: (res) => {
          console.log('获取连接wifi success', res);
          if (res.wifi) {
            updateWifiToModel(res.wifi.SSID);
            // setSsid(res.wifi.SSID);
          } else {
            console.log('获取连接wifi失败', res);
            if (!configWifiModel.wifiName) {
              configWifiModel.getLastestUseWifiInfo();
            }
          }
        },
      })
    }
  }, [isUserInput, updateWifiToModel]);

  useEffect(() => {
    getSSID()
  }, []);

  const handleSSIDInput = useCallback((e) => {
    !isUserInput && setUseInput(true);
    setSsid(e.detail.value);
  }, [isUserInput]);

  const handlePasswordInput = useCallback((e) => {
    setPassword(e.detail.value);
  }, []);

  useEffect(() => {
    Taro.onAppShow((res) => {
      console.log('onAppShow', res);
      const systemInfo = getSystemInfoSync();
      if (systemInfo.platform === 'android') {
        const systemVersion = getSystemVersion(systemInfo.system);
        if (systemVersion) {
          if (systemVersion > 80.0 && systemInfo.locationAuthorized) {
            getSSID()
          }
        }
      } else {
        getSSID()
      }
    })
    Taro.startWifi({
      complete: (res) => {
        console.log('startWifi', res);
        getSSID();
      }
    });
    return () => {
      Taro.stopWifi();
    }
  }, [getSSID]);


  useEffect(() => {
    // 监听 Wi-Fi 变化
    if (isUserInput) {
      Taro.offWifiConnected(() => { });
    } else {
      Taro.onWifiConnected((res) => {
        setSsid(res.wifi.SSID);
      });
    }
  }, [isUserInput]);

  const goToNext = useCallback(() => {
    if (!ssid || ssid.length < 0) {
      Toast.info(i18n.t('INPUT_WIFI'));
      return;
    }
    if (!password || password.length < 0) {
      Toast.info(i18n.t('INPUT_WIFI_PASSWORD'));
      return;
    }
    configWifiModel.updateWifiInfo({ wifiName: ssid, password: password, isManualInput: isUserInput });
    if (addWifi) {
      // 如果是配网页面快捷配置，这里添加
      const pages = Taro.getCurrentPages();
      const current = pages[pages.length - 1];
      const eventChannel = current.getOpenerEventChannel();
      eventChannel.emit('confirmEventKey', {});
      Taro.navigateBack();
    } else {
      setTimeout(() => {
        Taro.navigateTo({ url: '/pages/configDevice/addTip/index' });
      }, 100)
    }
  }, [password, ssid, addWifi, isUserInput])

  return (
    <PageContainer title={i18n.t('ADD_DEVICE')} style={styles.page}>
      <View style={styles.container}>
        <View>
          <DashedTitle title={i18n.t('INPUT_WIFI_PASSWORD')} num={1} isDashed />
          <View style={styles.desc}>
            {tips.map((tip) => (
              <TipItem {...tip} key={tip.text} text={i18n.t(tip.text)} />
            ))}
            {locationTip && <TipItem {...locationTip} text={i18n.t(locationTip.text)} />}
          </View>
          <View style={{ padding: 20 }}>
            <IconInput
              value={ssid}
              icon={wifiIcon}
              placeholder={i18n.t('INPUT_WIFI')}
              onInput={handleSSIDInput}
            />
            <IconInput
              icon={passwordIcon}
              // password
              placeholder={i18n.t('INPUT_WIFI_PASSWORD')}
              value={password}
              onInput={handlePasswordInput}
            />
          </View>
        </View>
        <GButton id='CONFIG_NEXT' text={i18n.t('NEXT')} onPress={goToNext} />
      </View>
    </PageContainer>
  );
};

export default SelectWifiPage;
